package hcb.dms.soDoTuyen;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import hcb.dms.JSONParser;
import hcb.dms.R;
import hcb.dms.UserSessionManager;



public class Dm_soDoTuyen extends Activity {

    Activity activity = null;
    private String id_soDoTuyen = "";
    private String tenTuyen = "";
    private String soLuong = "";
    private ListView lv;

    private ProgressDialog pDialog;


    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_SODOTUYEN = "soDoTuyen";
    private static final String TAG_ID = "id";
    private static final String TAG_MAKH = "maKH";
    private static final String TAG_TENKH = "tenKH";
    private static final String TAG_DIACHI = "diaChi";
    private static final String TAG_PHANHOI = "phanHoi";
    private static final String TAG_GPSLAT = "gpsLat";
    private static final String TAG_GPSLONG = "gpsLong";
    private static final String TAG_NGAY = "ngay";
    private static final String TAG_MANV = "maNV";
    private static final String TAG_MATUYEN = "maTuyen";
    private static final String TAG_TENTUYEN = "tenTuyen";
    private static final String TAG_SOLUONG = "soLuong";
    private String m_Text = "";

    // products JSONArray
    JSONArray products = null;
    UserSessionManager session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dm_so_do_tuyen);
        activity = this;//luu thong tin Activity
        session = new UserSessionManager(getApplicationContext());
        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        new LoadDanhSachTuyen().execute();

        // Get listview
        //   ListView lv = getListView();
        lv = (ListView) findViewById(R.id.list);
        this.registerForContextMenu(lv);// Dang ky ContextMenu in ListView
        // on seleting single product
        // launching Edit Product Screen

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String pid = ((TextView) view.findViewById(R.id.txMaTuyen)).getText().toString();
                id_soDoTuyen = pid ;
                activity.openContextMenu(lv);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.dm_so_do_tuyen, menu);
        return true;
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId() == R.id.list) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.dm_so_do_tuyen, menu);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.add) {
            Toast.makeText(this, "Them moi ", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Title");

            // Set up the input
            final EditText input = new EditText(this);
            // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
            input.setInputType(InputType.TYPE_CLASS_TEXT);
            builder.setView(input);

            // Set up the buttons
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                m_Text = input.getText().toString();
                new NewSoDoTuyen().execute();
            }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
            });

            builder.show();

        }
        else if (item.getItemId() == R.id.add_khach_hang) {
            Toast.makeText(this, "Them khach hang vao tuyen ", Toast.LENGTH_SHORT).show();
        }
        else if (item.getItemId() == R.id.chi_tiet_so_do_tuyen) {
            Toast.makeText(this, "Cac khach hang trong tuyen ", Toast.LENGTH_SHORT).show();

        }else if (item.getItemId() == R.id.edit) {
            Toast.makeText(this, "Sua du lieu ", Toast.LENGTH_SHORT).show();
            // Starting new intent
            Intent in = new Intent(getApplicationContext(), Edit_soDoTuyen.class);
            // sending pid to next activity
            in.putExtra(TAG_ID, id_soDoTuyen);
            in.putExtra(TAG_TENTUYEN, tenTuyen);
            in.putExtra(TAG_SOLUONG, soLuong);
            // starting new activity and expecting some response back
            startActivityForResult(in, 100);

        } else if (item.getItemId() == R.id.delete) {
            Toast.makeText(this, "Xoa du lieu", Toast.LENGTH_SHORT).show();
        } else {
            return false;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String text = "ID: " + item.getItemId()
                + " title: " + item.getTitle();
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        return true;
    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     */
    class LoadDanhSachTuyen extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            pDialog = new ProgressDialog(Dm_soDoTuyen.this);
            pDialog.setMessage("Loading danh sách tuyến. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        /**
         * getting All products from url
         */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
            params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
            params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
            params.add(new BasicNameValuePair(session.TAG_THAOTAC, "LDSSDT"));
        //   params.add(new BasicNameValuePair(TAG_NGAY, ""));

            params.add(new BasicNameValuePair(TAG_MANV, session.getUsername()));

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(session.URL, "POST", params);
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {

                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_SODOTUYEN);
                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);
                        String ma = c.getString(TAG_MATUYEN);
                        String ten = c.getString(TAG_TENTUYEN);
                        String so = c.getString(TAG_SOLUONG);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put(TAG_MATUYEN, ma);
                        map.put(TAG_TENTUYEN, ten);
                        map.put(TAG_SOLUONG, so);
                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    //		Intent i = new Intent(getApplicationContext(),Edit_khuVuc.class);
                    // Closing all previous activities
                    //		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //		startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
               // Log.d("All ds tuyen of nhan vien: ", json.toString());
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    Log.d("Danh sach tuyen : ", "abc");
                    ListAdapter adapter = new SimpleAdapter(
                            Dm_soDoTuyen.this, productsList,
                            R.layout.item_so_do_tuyen, new String[]{ TAG_MATUYEN, TAG_TENTUYEN, TAG_SOLUONG}, new int[]
                            { R.id.txMaTuyen, R.id.txTenTuyen, R.id.txSoLuong});
                    // updating listview
                    lv = (ListView) findViewById(R.id.list);
                    lv.setAdapter(adapter);
                }
            });

        }
    }
    class NewSoDoTuyen extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            pDialog = new ProgressDialog(Dm_soDoTuyen.this);
            pDialog.setMessage("Loading danh sách tuyến. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        /**
         * getting All products from url
         */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
            params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
            params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
            params.add(new BasicNameValuePair(session.TAG_THAOTAC, "NSDT"));
            params.add(new BasicNameValuePair(TAG_TENTUYEN,m_Text.toString()));
            //   params.add(new BasicNameValuePair(TAG_NGAY, ""));
            params.add(new BasicNameValuePair(TAG_MANV, session.getUsername()));

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(session.URL, "POST", params);
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {

                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_SODOTUYEN);
                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);
                        String ma = c.getString(TAG_MATUYEN);
                        String ten = c.getString(TAG_TENTUYEN);
                        String so = c.getString(TAG_SOLUONG);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put(TAG_MATUYEN, ma);
                        map.put(TAG_TENTUYEN, ten);
                        map.put(TAG_SOLUONG, so);
                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    //		Intent i = new Intent(getApplicationContext(),Edit_khuVuc.class);
                    // Closing all previous activities
                    //		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //		startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                // Log.d("All ds tuyen of nhan vien: ", json.toString());
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    Log.d("Danh sach tuyen : ", "abc");
                    ListAdapter adapter = new SimpleAdapter(
                            Dm_soDoTuyen.this, productsList,
                            R.layout.item_so_do_tuyen, new String[]{ TAG_MATUYEN, TAG_TENTUYEN, TAG_SOLUONG}, new int[]
                            { R.id.txMaTuyen, R.id.txTenTuyen, R.id.txSoLuong});
                    // updating listview
                    lv = (ListView) findViewById(R.id.list);
                    lv.setAdapter(adapter);
                }
            });

        }
    }
}